#!/bin/bash
# Run local pre-commit hook
#
# If called directly, installs a pre-commit hook

set -o errexit

WD=$(dirname $0)
WD=$(cd $WD; pwd)
ROOT=$(dirname $WD)
if [[ $ROOT == */.git ]]; then
  ROOT=$ROOT/..
fi

# Not running under git commit
# install handler
if [[ -z ${GIT_AUTHOR_DATE} ]];then
  cd $ROOT/.git/hooks/
  if !([[ -e pre-commit ]] || [[ -h pre-commit ]]); then
    echo "Installing pre-commit hook"
    ln -s $ROOT/scripts/pre-commit
  else
    echo "Hook already installed"
  fi
  exit 0
fi

# If we don't have a branch then we're in a detached state (e.g. mid rebase) and don't want to execute our checks.
BRANCH_NAME=$(git branch | grep '*' | sed 's/* //')
if [ $BRANCH_NAME != '(no branch)' ]; then
  cd $ROOT

  echo "generating pb.go files..."
  scripts/generate-protos.sh
fi
